package com.rockwell.modbus800;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	UsbManager m_UsbManager;
	
	ModbusSerialClient m_modbus;

	public static MainActivity mMainActivity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
        m_UsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		m_modbus = new ModbusSerialClient(m_UsbManager);
		
		mMainActivity = this;
		
		setupConnectButton();
		setupDisconnectButton();
		setupWriteButton();
		setupReadButton();
		setupClearLogButton();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public static void WriteMessage(final String msg) {
	    MainActivity.mMainActivity.runOnUiThread(new Runnable() {
	
	        public void run() {
	            //Toast.makeText(MainActivity.mMainActivity, msg, Toast.LENGTH_SHORT).show();
	    		TextView tv = (TextView)MainActivity.mMainActivity.findViewById(R.id.text_error);
	    		String eol = System.getProperty("line.separator");  
	    		tv.append(eol);
	    		tv.append(msg);
	        }
	    });
	}

	private void setupConnectButton() {
		Button b = (Button)findViewById(R.id.button_connection);
		
		b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				connect();
			}
			
		});
	}

	private void setupDisconnectButton() {
		Button b = (Button)findViewById(R.id.button_disconnection);
		
		b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				disconnect();
			}
			
		});
	}

	private void setupWriteButton() {
		Button b = (Button)findViewById(R.id.button_write);
		
		b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				write();
			}
			
		});
	}

	private void setupReadButton() {
		Button b = (Button)findViewById(R.id.button_read);
		
		b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				read();
			}
			
		});
	}

	private void setupClearLogButton() {
		Button b = (Button)findViewById(R.id.button_clear_log);
		
		b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				TextView tv = (TextView)findViewById(R.id.text_error);
				tv.setText("");
			}
			
		});
	}

	private void connect() {
		EditText edit = (EditText)findViewById(R.id.com_port);
		
		try {
			m_modbus.connect(edit.getText().toString());
			
			TextView tv = (TextView)findViewById(R.id.label_connectedness);
			tv.setText("connected");
			
			clearError();
		}
		catch (Throwable e) {
			showError(e);
		}
	}
	
	private void disconnect() {
		try {
			m_modbus.disconnect();
			
			TextView tv = (TextView)findViewById(R.id.label_connectedness);
			tv.setText("disconnected");
			
			clearError();
		}
		catch (Throwable e) {
			showError(e);
		}
	}
	
	private void write() {
		EditText ref = (EditText)findViewById(R.id.edit_ref);
		EditText value = (EditText)findViewById(R.id.edit_value);
		
		try {
			m_modbus.writeHoldingRegister(
					Integer.parseInt(ref.getText().toString()), 
					Integer.parseInt(value.getText().toString()));
			clearError();
		}
		catch (Throwable e) {
			showError(e);
		}
	}
	
	private void read() {
		EditText ref = (EditText)findViewById(R.id.edit_ref);
		EditText value = (EditText)findViewById(R.id.edit_value);
		
		try {
			int v = m_modbus.readHoldingRegister(
					Integer.parseInt(ref.getText().toString()));
			
			value.setText(Integer.toString(v));
			clearError();
		}
		catch (Throwable e) {
			showError(e);
		}
	}
	
	private void clearError() {
		TextView tv = (TextView)findViewById(R.id.text_error);
		//tv.setText("");
	}
	
	private void showError(Throwable e) {
		e = getInnerError(e);

		TextView tv = (TextView)findViewById(R.id.text_error);
		tv.append(e.getMessage());

		String eol = System.getProperty("line.separator");  
		tv.append(eol);
		
		tv.append(toString(e.getStackTrace()));
	}

	private Throwable getInnerError(Throwable e) {
		while (e.getCause() != null) {
			e = e.getCause();
		}
		
		return e;
	}
	
	public static String toString(StackTraceElement[] stackTraceElements) {
	    if (stackTraceElements == null)
	        return "";
	    StringBuilder stringBuilder = new StringBuilder();
	    for (StackTraceElement element : stackTraceElements)
	        stringBuilder.append(element.toString()).append("\n");
	    return stringBuilder.toString();
	}
}
